package com.jetinno.simple;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.jetinno.utils.LoadMvpView;
import com.jetinno.utils.LocalManageUtil;
import com.jetinno.utils.LogUtils;
import com.jetinno.utils.ScreenUtil;
import com.jetinno.utils.SimpleCallback;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;


/**
 * Created by zhangyuncai on 2021/11/11.
 */
public abstract class SimpleActivity extends FragmentActivity implements LoadMvpView {

    protected String TAG = this.getClass().getSimpleName();
    protected CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    private boolean filterDoubleDown = true;//是否过滤同时点击屏幕
    private ActivityListener activityListener = null;

    protected boolean isRegisterEventBus = false;
    protected final List<SimplePresenter> presenters = new ArrayList<>();

    protected Context getContext() {
        return this;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.INSTANCE.attachBaseContextLang(newBase));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isThemeDialog()) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setFinishOnTouchOutside(isOnTouchOutside());
        }
        setContentView(getLayoutId());
        if (isThemeDialog()) {
            WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
            layoutParams.width = getWidthStyle();
            layoutParams.height = getHeightStyle();
            layoutParams.gravity = getGravity();
            layoutParams.dimAmount = 0.8f;//设置黑暗度
            getWindow().setAttributes(layoutParams);
        }
        findViewByIds();
        if (isRegisterEventBus) {
            EventBus.getDefault().register(this);
        }
        initView();
        initEvent();
        initData();
        if (getApplication() instanceof ActivityListener) {
            activityListener = (ActivityListener) getApplication();
        }
    }

    protected abstract int getLayoutId();

    protected void addPresenter(SimplePresenter presenter) {
        presenters.add(presenter);
    }

    protected void findViewByIds() {
    }

    protected abstract void initView();

    protected abstract void initEvent();

    protected void addOnClick(int... ids) {
        for (int id : ids) {
            findViewById(id).setOnClickListener(v -> {
                onClick(v);
            });
        }
    }

    public void onClick(View v) {

    }

    protected abstract void initData();

    protected Disposable delay(long delay, SimpleCallback<Object> callback) {
        Disposable subscribe = Observable.timer(delay, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    callback.callback(true);
                }, throwable -> {
                    LogUtils.logException(TAG, throwable);
                });
        mCompositeDisposable.add(subscribe);
        return subscribe;
    }

    /*-------------------------否是dialog---------------------*/
    /*-------------------------否是dialog---------------------*/

    /**
     * 界面是否是dialog的形式,是否可以点击外部关闭dialog
     *
     * @return
     */
    protected boolean isOnTouchOutside() {
        return false;
    }

    /**
     * 界面是否是dialog的形式
     *
     * @return
     */
    protected boolean isThemeDialog() {
        return false;
    }

    @FloatRange(from = 0.0, to = 1.0)
    protected double getWidthPercent() {
        return DialogPx.getWidthPercent();
    }

    protected int getWidthStyle() {
        double widthPercent = getWidthPercent();
        if (widthPercent > 0 && widthPercent < 1) {
            return (int) (ScreenUtil.getScreenWidth(getContext()) * widthPercent);
        }
        return WindowManager.LayoutParams.MATCH_PARENT;
    }

    @FloatRange(from = 0.0, to = 1.0)
    protected double getHeightPercent() {
        return 0;
    }

    protected int getHeightStyle() {
        double heightPercent = getHeightPercent();
        if (heightPercent > 0 && heightPercent < 1) {
            return (int) (ScreenUtil.getScreenHeigth(getContext()) * heightPercent);
        }
        return WindowManager.LayoutParams.WRAP_CONTENT;
    }

    protected int getGravity() {
        return Gravity.CENTER;
    }
    /*-------------------------否是dialog---------------------*/
    /*-------------------------否是dialog---------------------*/


    /*-------------------------dispatchTouchEvent---------------------*/
    /*-------------------------dispatchTouchEvent---------------------*/
    private long lastTime = 0;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (activityListener != null) {
            activityListener.dispatchTouchEvent();
        }
        if (filterDoubleDown) {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                long l = System.currentTimeMillis();
                if ((l - lastTime) < 100) {
                    Timber.e("短时间多次双击忽略");
                    return true;
                }
                lastTime = l;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setFilterDoubleDown(boolean filterDoubleDown) {
        this.filterDoubleDown = filterDoubleDown;
    }
    /*-------------------------dispatchTouchEvent---------------------*/
    /*-------------------------dispatchTouchEvent---------------------*/

    /*-------------------------loading---------------------*/
    /*-------------------------loading---------------------*/
    private LoadingAbsDialog _processBar;

    @Override
    public void showLoadingBar(String msg) {
        Timber.e("showLoadingBar");
        runOnUiThread(() -> {
            if (_processBar == null) {
                try {
                    String className = "com.jetinno.widget.LoadingDialog";
                    Class<?> aClass = Class.forName(className);
                    Constructor<?> constructor = aClass.getConstructor(new Class[]{Context.class, String.class});
                    Object o = constructor.newInstance(this, msg);
                    if (o != null && o instanceof LoadingAbsDialog) {
                        _processBar = (LoadingAbsDialog) o;
                        _processBar.setCanceledOnTouchOutside(false);
                        _processBar.setSureCallback(new SimpleCallback<Object>() {
                            @Override
                            public void callback(Object o) {
                                dismissLoadingBar();
                            }
                        });
                        _processBar.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                Timber.e("onDismiss");
                            }
                        });
                        _processBar.show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                _processBar.setMessage(msg);
                if (!_processBar.isShowing()) {
                    Timber.e("showing");
                    _processBar.show();
                }
            }
        });
    }

    @Override
    public void dismissLoadingBar() {
        runOnUiThread(() -> {
            if (_processBar != null) {
                if (_processBar.isShowing()) {
                    _processBar.dismiss();
                }
                _processBar = null;
            }
        });
    }

    /*-------------------------loading---------------------*/
    /*-------------------------loading---------------------*/

    protected void onDestroy() {
        mCompositeDisposable.dispose();
        dismissLoadingBar();
        if (isRegisterEventBus) {
            EventBus.getDefault().unregister(this);
        }
        for (SimplePresenter presenter : presenters) {
            presenter.onDestory();
        }
        super.onDestroy();
    }
}
